package org.crazyit.test.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.crazyit.test.util.TokenAuthenticationUtil;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

public class AuthFilter extends ZuulFilter {

	@Override
	public Object run() {
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletResponse response = ctx.getResponse();
		// 设置路由状态，表示已经进行路由
		ctx.setResponseBody("没有token信息");
		// 设置响应标识
		ctx.sendZuulResponse();
		return null;
	}

	@Override
	public boolean shouldFilter() {
		
		System.err.println("======================通过网关=======================");
		
		RequestContext ctx = RequestContext.getCurrentContext();
		HttpServletRequest request = ctx.getRequest();
		
		String requestPath = request.getRequestURI(); // 请求的URL
		if("/auth".equals(requestPath) || "/routeTest".equals(requestPath) || "/refresh".equals(requestPath)) {
			return false;
		}
		
		String token = request.getParameter("token");
		
		if(token == null) {
			System.out.println("token为null");
			return true;
		}
		
		String authentication = TokenAuthenticationUtil.getAuthentication(token);
		System.out.println("authentication: " + authentication);
		return false;
	}

	@Override
	public int filterOrder() {
		return 0;
	}

	@Override
	public String filterType() {
		return FilterConstants.PRE_TYPE;
	}

}
